package com.itheima.health.task;

import com.itheima.health.dao.SetMealDao;
import com.itheima.health.pojo.entity.Setmeal;
import com.itheima.health.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class AliossTask {
    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private SetMealDao setMealDao;

    @Scheduled(cron = "0 0 2 * * ?")
    public void cleanImage() {
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(aliOssUtil.getBucketName())
                .append(".")
                .append(aliOssUtil.getEndpoint())
                .append("/");
        String imagePre = stringBuilder.toString();
        List<Setmeal> setmealList = setMealDao.selectAll();
        List<String> setImage = setmealList.stream().map(e -> {
            if (e.getImg().contains(imagePre)) {
                return e.getImg().replace(imagePre, "");
            }
            return null;
        }).collect(Collectors.toList());
        List<String> fileNames=aliOssUtil.listObjects();
        fileNames.removeAll(setImage);
        aliOssUtil.deleteFiles(fileNames);
    }
}
